package com.jcnet.bizaia;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.http.Header;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jcnet.bizaia.bean.BusinessCategoryBean;
import com.jcnet.bizaia.bean.SPUserBean;
import com.jcnet.bizaia.bean.SearchBean;
import com.jcnet.bizaia.bean.StateBean;
import com.jcnet.bizaia.commCategory.BusinessCategoryList;
import com.jcnet.bizaia.tools.JCTools;
import com.jcnet.bizaia.tools.Toolkit;
import com.jcnet.bizaia.view.ProgressHUD;
import com.jcnet.bizaia.xstream.ACache;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

public class SettingUserMenuActivity extends JCSimpleSherlockActivity implements OnItemClickListener{

	private BroadcastReceiver broadcastReceiver;

	private GridView discussCategoryGridView;
	private GridView userdiscussCategoryGridView;
	private GridView vodCategoryGridView;
	private GridView uservodCategoryGridView;

	private List<SearchBean> dicussBeans = new ArrayList<SearchBean>();   //讨论会数据集合
	private List<SearchBean> userdicussBeansU1 = new ArrayList<SearchBean>();   //讨论会数据集合
	private List<SearchBean> vodBeans = new ArrayList<SearchBean>();   //VOd数据集合
	private List<SearchBean> uservodBeansU2 = new ArrayList<SearchBean>();   //VOd数据集合

	private GridViewAdapter discussGridViewAdapter;
	private GridViewAdapter userdiscussGridViewAdapter;
	private GridViewAdapter vodGridViewAdapter;
	private GridViewAdapter uservodGridViewAdapter;

	private Context context;

	private int mark = 1;  // 分类编号标记  1 2 3 


	private ACache aCache;
	
	public static final String SETTING_USER_CATEGORY = App.HTTP_PATH+"usind_showUserindustryAll.action?";

	public static String[] categoryNames ={"D","DU!","V","VU"};
	
	private ProgressHUD progressHUD;
	
	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		super.jcTitle =getString(R.string.setting);
		super.jcSubtitle = getString(R.string.myMenu);
		super.initActionBar();
		setContentView(R.layout.setting_user_menu);

		
		context = this;
		
		aCache = ACache.get(this);

		discussCategoryGridView = (GridView)findViewById(R.id.discussCategoryGridView);
		userdiscussCategoryGridView = (GridView)findViewById(R.id.userdiscussCategoryGridView);
		vodCategoryGridView =(GridView)findViewById(R.id.vodCategoryGridView);
		uservodCategoryGridView =(GridView)findViewById(R.id.uservodCategoryGridView);



		discussGridViewAdapter = new GridViewAdapter(dicussBeans);
		vodGridViewAdapter = new GridViewAdapter(vodBeans);
		
		userdiscussGridViewAdapter = new GridViewAdapter(userdicussBeansU1);
		uservodGridViewAdapter = new GridViewAdapter(uservodBeansU2);


		discussCategoryGridView.setAdapter(discussGridViewAdapter);
		vodCategoryGridView.setAdapter(vodGridViewAdapter);

		userdiscussCategoryGridView.setAdapter(userdiscussGridViewAdapter);
		uservodCategoryGridView.setAdapter(uservodGridViewAdapter);
		
		
		discussCategoryGridView.setOnItemClickListener(this);
		vodCategoryGridView.setOnItemClickListener(this);
		userdiscussCategoryGridView.setOnItemClickListener(this);
		uservodCategoryGridView.setOnItemClickListener(this);
		 

		



		broadcastReceiver = new BroadcastReceiver() {

			@Override
			public void onReceive(Context context, Intent intent) {
				// TODO Auto-generated method stub


				if(intent.getAction()==VodSearchActivity.RECEIVER_VODSEARCHACTIVITY){
					mark = intent.getIntExtra("mark", -404);
					System.out.println("mark:"+mark);
					switch (mark) {
					case 1:
						List<BusinessCategoryBean> catgoryBeans = (List<BusinessCategoryBean>) intent.getExtras().getSerializable("AllBusinessCategoryLisyBean");
						
						Set<String>setStrings = new HashSet<String>();
						
						if(catgoryBeans!=null){
							dicussBeans.clear();
							for (BusinessCategoryBean catgoryBean : catgoryBeans) {
								SearchBean searchBean1 = 	new SearchBean(catgoryBean.getIndustryname(), catgoryBean.getIid());
								
								if(!userdicussBeansU1.contains(searchBean1)){
									dicussBeans.add(searchBean1);
									setStrings.add(catgoryBean.getIndustryname()+","+catgoryBean.getIid());
								}
							}
							
							
						}
						
						JCTools.putSettingUserCategory(context, categoryNames[0], setStrings);

						discussGridViewAdapter.count = dicussBeans.size();
						discussGridViewAdapter.notifyDataSetChanged();
						initVodCategory();

						break;
					case  2:
						List<BusinessCategoryBean> catgoryBeans2 = (List<BusinessCategoryBean>) intent.getExtras().getSerializable("AllBusinessCategoryLisyBean");
						
						Set<String>setStrings2 = new HashSet<String>();
						if(catgoryBeans2!=null){
							vodBeans.clear();
							for (BusinessCategoryBean catgoryBean : catgoryBeans2) {
							 SearchBean searchBean = 	new SearchBean(catgoryBean.getIndustryname(), catgoryBean.getIid());
								if(!uservodBeansU2.contains(searchBean)){
								vodBeans.add(searchBean);
								setStrings2.add(catgoryBean.getIndustryname()+","+catgoryBean.getIid());
								}
							}
						}

						JCTools.putSettingUserCategory(context, categoryNames[1], setStrings2);
						
						vodGridViewAdapter.count = vodBeans.size();
						vodGridViewAdapter.notifyDataSetChanged();

						break;
					


					default:
						break;
					}

				}

			}
		};

		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(VodSearchActivity.RECEIVER_VODSEARCHACTIVITY);
		registerReceiver(broadcastReceiver, intentFilter);


		
		
		httpGetSettingUserCategoryBean();


	}


	private void initVodCategory() {
		// TODO Auto-generated method stub
		RequestParams params = new RequestParams();
		params.put("languageNum", App.localeCode+"");
		params.put("midNum", 2+"");  
		new  BusinessCategoryList(context, params,2).getAllCategory();

	}

	private void initDiscussCategory() {
		// TODO Auto-generated method stub
		RequestParams params = new RequestParams();
		params.put("languageNum", App.localeCode+"");
		params.put("midNum", 1+"");  
		new  BusinessCategoryList(context, params,1).getAllCategory();
	}



	/**
	 * 
	 * @author chenguandong
	 * 讨论会分类的Adapter
	 *
	 */
	class GridViewAdapter extends BaseAdapter{


		private List<SearchBean> discussBeans ;
		public int count;
		public GridViewAdapter(List<SearchBean> discussBeans ) {
			super();
			// TODO Auto-generated constructor stub
			this.discussBeans = discussBeans;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			count = discussBeans.size();
			return count;
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHodel viewHodel = null;
			if(convertView==null){
				viewHodel = new ViewHodel();
				convertView = View.inflate(context, R.layout.gridview_text_lay, null);
				viewHodel.textView = (TextView)convertView.findViewById(R.id.gridViewTextView);
				convertView.setTag(viewHodel);
			}else{
				viewHodel = (ViewHodel) convertView.getTag();
			}

			viewHodel.textView.setText(discussBeans.get(position).getSearchName());

			return convertView;
		}


		class ViewHodel{
			TextView textView;
		}
	}



	private void	httpGetSettingUserCategoryBean(){
		
		final RequestParams params = new RequestParams();
		params.put("languageNum", App.localeCode+"");
		params.put("useridNum", getSharedPreferences(SPUserBean.dataTableNameForUser, MODE_PRIVATE).getInt(SPUserBean.userIDSP_1, -400)+"");  
		//new  BusinessCategoryList(context, params,App.HTTP_PATH+"usind_showUserindustryAll.action?").getAllCategory();
		if(Toolkit.isAvaliable(context)){

			
			//有网络请求数据
			new AsyncHttpClient().post(SETTING_USER_CATEGORY, params, new AsyncHttpResponseHandler(){
				
				@Override
				public void onStart() {
					// TODO Auto-generated method stub
					super.onStart();
					
					
				}
				
				
				@Override
				public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
					// TODO Auto-generated method stub
					super.onSuccess(arg0, arg1, arg2);
					
					String requestString  = new String(arg2);
					
					if(requestString!=null){
						aCache.put(SETTING_USER_CATEGORY+params, requestString,App.CACHE_TIME_DAY_VERY_SHORT);
						setListData(requestString);
					}
					
					
				}
				
				@Override
				public void onFailure(int arg0, Header[] arg1, byte[] arg2,
						Throwable arg3) {
					// TODO Auto-generated method stub
					super.onFailure(arg0, arg1, arg2, arg3);
					Toast.makeText(context, context.getString(R.string.serverError), 0).show();
					
				}
				
				
				@Override
				public void onFinish() {
					// TODO Auto-generated method stub
					super.onFinish();
					initDiscussCategory();   //访问总的订阅 飞用户
					
					
					
					
				}
			});
		
		}else{

			
			//没有网络就离线缓存

			String 
			
			requestString = aCache.getAsJSONObject(SETTING_USER_CATEGORY+params).toString();
			
			if(requestString!=null){
				
				 setListData(requestString);
			}else{
				Toast.makeText(context, context.getString(R.string.noData), 0).show();
			}
			
		
		}
	}


	
	private List<BusinessCategoryBean>  setListData(String arg2){
		
		String requestString = arg2;

		System.out.println(requestString+"-------------------------");
		AllBusinessRequestHttpData requestBeanRequest = new AllBusinessRequestHttpData();

		//System.out.println("byte:"+new String(arg2));

		if(requestString!=null){
			
			requestBeanRequest = new Gson().fromJson(requestString, new TypeToken<AllBusinessRequestHttpData>(){}.getType());

			if(requestBeanRequest.getState()==200){
				
				
				
				List<BusinessCategoryBean> catgoryBeans3 = (List<BusinessCategoryBean>) requestBeanRequest.getObjlistJson();

				if(catgoryBeans3!=null){
					userdicussBeansU1.clear();
					uservodBeansU2.clear();
					Set<String> uss= new HashSet<String>();
					Set<String> uss2= new HashSet<String>();
					for (BusinessCategoryBean catgoryBean : catgoryBeans3) {
						if(catgoryBean.getMid()==1){
							
						 SearchBean searchBean = 	new SearchBean(catgoryBean.getIndustryname(), catgoryBean.getIid());
							
							 userdicussBeansU1.add(searchBean);
							
							System.out.println("my self add:"+catgoryBean.getIndustryname());
							uss.add(catgoryBean.getIndustryname()+""+catgoryBean.getIid());
						}

						if(catgoryBean.getMid()==2){
							SearchBean searchBean = new SearchBean(catgoryBean.getIndustryname(), catgoryBean.getIid());
							uservodBeansU2.add(searchBean);
							System.out.println("my self add2:"+catgoryBean.getIndustryname());
							uss2.add(catgoryBean.getIndustryname()+""+catgoryBean.getIid());
						}
					}
					
					JCTools.putSettingUserCategory(context, categoryNames[2], uss);
					JCTools.putSettingUserCategory(context, categoryNames[3], uss2);

					System.out.println("you are sure refresh?");

				}

				userdiscussGridViewAdapter.count = userdicussBeansU1.size();
				userdiscussGridViewAdapter.notifyDataSetChanged();

				uservodGridViewAdapter.count = uservodBeansU2.size();
				uservodGridViewAdapter.notifyDataSetChanged();

			}

		}
		
		
		return null;
		
	}
	
	
	class AllBusinessRequestHttpData{
		private int state;

		private String message;

		private List<BusinessCategoryBean> objlistJson;

		public int getState() {
			return state;
		}

		public void setState(int state) {
			this.state = state;
		}

		public String getMessage() {
			return message;
		}

		public void setMessage(String message) {
			this.message = message;
		}

		public List<BusinessCategoryBean> getObjlistJson() {
			return objlistJson;
		}

		public void setObjlistJson(List<BusinessCategoryBean> objlistJson) {
			this.objlistJson = objlistJson;
		}


	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub

		super.onDestroy();
		unregisterReceiver(broadcastReceiver);
	}
	
	
	private void addUserMenu(int iidNum,  int midNum){
		if(Toolkit.isAvaliable(context)){
			/**
			 * 参数名称	参数类型	说明
					iidNum	int	订阅行业ID
					midNum	int	所属菜单编号
					useridNum	int	用户ID
			 */
			RequestParams params = new RequestParams();
			params.put("iidNum", iidNum+"");
			params.put("midNum", midNum+"");
			params.put("useridNum", JCTools.getUserID(context));  //用户ID
			
			new AsyncHttpClient().post(App.HTTP_PATH+"usind_addUserindustry.action?", params, new AsyncHttpResponseHandler(){
				
				@Override
				public void onStart() {
					// TODO Auto-generated method stub
					progressHUD = ProgressHUD.show(context, getString(R.string.commiting), true	, false, null);
					super.onStart();
				}
				
				
				@Override
				public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
					// TODO Auto-generated method stub
					super.onSuccess(arg0, arg1, arg2);
					
					StateBean stateBean = new Gson().fromJson(new String(arg2), new TypeToken<StateBean>(){}.getType());
				
					if(stateBean.getState()==200){
						Toast.makeText(context, getString(R.string.addSuccess), 0).show();
						
						
					}else{
						Toast.makeText(context, stateBean.getMessage()+"", 0).show();
					}
				}
				
				
				@Override
				public void onFinish() {
					// TODO Auto-generated method stub
					super.onFinish();
					if(progressHUD.isShowing()){
						progressHUD.cancel();
					}
				}
				
				@Override
				public void onFailure(int arg0, Header[] arg1, byte[] arg2,
						Throwable arg3) {
					// TODO Auto-generated method stub
					super.onFailure(arg0, arg1, arg2, arg3);
					if(progressHUD.isShowing()){
						progressHUD.cancel();
					}
					Toast.makeText(context, getText(R.string.serverError), 0).show();
				}
			});
			
			
		}else{
			Toast.makeText(context, R.string.noNetWork, 0).show();
		}
		
	}
	private void delUserMenu(int iidNum,  int midNum){
		if(Toolkit.isAvaliable(context)){
			/**
			 * 参数名称	参数类型	说明
				iidNum	int	订阅行业ID
				useridNum	int	用户ID
			 */
			RequestParams params = new RequestParams();
			params.put("iidNum", iidNum+"");
			params.put("useridNum", JCTools.getUserID(context));  //用户ID
			
			new AsyncHttpClient().post(App.HTTP_PATH+"usind_delelteUserindustry.action?", params, new AsyncHttpResponseHandler(){
				
				@Override
				public void onStart() {
					// TODO Auto-generated method stub
					progressHUD = ProgressHUD.show(context, getString(R.string.commiting), true	, false, null);
					super.onStart();
				}
				
				@Override
				public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
					// TODO Auto-generated method stub
					super.onSuccess(arg0, arg1, arg2);
					
					StateBean stateBean = new Gson().fromJson(new String(arg2), new TypeToken<StateBean>(){}.getType());
					
					if(stateBean.getState()==200){
						Toast.makeText(context, getString(R.string.delSuccess), 0).show();
						
						
					}else{
						Toast.makeText(context, stateBean.getMessage()+"", 0).show();
					}
				}
				
				
				@Override
				public void onFinish() {
					// TODO Auto-generated method stub
					super.onFinish();
					if(progressHUD.isShowing()){
						progressHUD.cancel();
					}
				}
				
				@Override
				public void onFailure(int arg0, Header[] arg1, byte[] arg2,
						Throwable arg3) {
					// TODO Auto-generated method stub
					super.onFailure(arg0, arg1, arg2, arg3);
					if(progressHUD.isShowing()){
						progressHUD.cancel();
					}
					Toast.makeText(context, getText(R.string.serverError), 0).show();
				}
			});
			
			
		}else{
			Toast.makeText(context, R.string.noNetWork, 0).show();
		}
		
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		switch (parent.getId()) {
		case R.id.discussCategoryGridView:
			
			addUserMenu(dicussBeans.get(position).getSearchID(), App.discussMIDNum);
			
			
			userdicussBeansU1.add(dicussBeans.get(position));
			dicussBeans.remove(position);
			
			//刷新  讨论会
			discussGridViewAdapter.count = dicussBeans.size();
			discussGridViewAdapter.notifyDataSetChanged();
			
			//刷新用户讨论会
			userdiscussGridViewAdapter.count = userdicussBeansU1.size();
			userdiscussGridViewAdapter.notifyDataSetChanged();
			
			
			
			break;
		case R.id.userdiscussCategoryGridView:
			delUserMenu(userdicussBeansU1.get(position).getSearchID(), App.discussMIDNum);
			dicussBeans.add(userdicussBeansU1.get(position));
			userdicussBeansU1.remove(position);
			
			//刷新  讨论会
			discussGridViewAdapter.count = dicussBeans.size();
			discussGridViewAdapter.notifyDataSetChanged();
			
			//刷新用户讨论会
			userdiscussGridViewAdapter.count = userdicussBeansU1.size();
			userdiscussGridViewAdapter.notifyDataSetChanged();
			
			
			break;
		case R.id.vodCategoryGridView:
			addUserMenu(vodBeans.get(position).getSearchID(), App.vodMIDNum);
			uservodBeansU2.add(vodBeans.get(position));
			vodBeans.remove(position);
			
			
			//刷新  讨论会
			vodGridViewAdapter.count = vodBeans.size();
			vodGridViewAdapter.notifyDataSetChanged();
			
			//刷新用户讨论会
			uservodGridViewAdapter.count = uservodBeansU2.size();
			uservodGridViewAdapter.notifyDataSetChanged();
			break;
		case R.id.uservodCategoryGridView:
			delUserMenu(uservodBeansU2.get(position).getSearchID(), App.vodMIDNum);
			vodBeans.add(uservodBeansU2.get(position));
			uservodBeansU2.remove(position);
			
			//刷新  讨论会
			vodGridViewAdapter.count = vodBeans.size();
			vodGridViewAdapter.notifyDataSetChanged();
			
			//刷新用户讨论会
			uservodGridViewAdapter.count = uservodBeansU2.size();
			uservodGridViewAdapter.notifyDataSetChanged();
			
			break;

		default:
			break;
		}
	}
}
